<?php

namespace app\api\controller\customer;

use app\api\controller\Base;
use app\api\controller\Pub;
use app\api\controller\pub\Yunke;
use app\api\controller\pub\Teltool;
use app\api\controller\pub\Telpcphone;
use app\api\controller\pub\Yhpcsoftasr;
use app\api\controller\pub\Siliconflow;
use app\common\model\company\Company;
use app\common\model\customer\Customer as Customermodel;
use app\common\model\customer\Customervisit;
use app\common\model\customer\Subscribe as SubscribeModel;
use app\common\model\apiinput\Apiyunkerecords;
use app\common\model\apiinput\Apiyunkefriends;
use app\common\model\apiinput\Apiyunkeaccounts;
use app\common\model\power\Rolepower;
use app\common\model\pub\Telbind;
use app\common\model\user\User as UserModel;
use think\facade\Cache;
use think\facade\Env;

class Customer extends Base
{
    /**
     * 产生jwt加密串，参考session
     */
    public function initialize()
    {
        parent::initialize();
        self::is_login();
        Rolepower::powerguard(201003);
    }

    /**
     * 建立 pc 与手机连接的 token
     * @return [type] [description]
     */
    public function get_start_link(){
        return myok(Telpcphone::get_start_link());
    }

    /**
     * 呼叫客户（被叫）
     * @return [type] [description]
     */
    public function callout(){
        $tel = input('tel');
        $myuser = Telbind::get(Pub::userid());
        if(empty($myuser)){
            return moerr('没有找到您的呼叫坐席');
        }
        $teltool = new TelTool();
        $req = $teltool->dial($tel,$myuser->Iphone);
        if (!$req['code']) {
            return myok(['call_center'=>'error','msg'=>$req['msg'],'tel'=>$tel]);
        }else{
            return myok(['call_center'=>'success','msg'=>'已通知回拨中心，请等待接听电话','tel'=>$tel]);
        }
    }

    

    public function day_summary(){
        //将客户名称，沟通内容，沟通信息存储后发给ai 让其总结
        $data = self::summary_data();
        foreach ($data['list'] as $key => $value) {
            $ndata['企业名称'] = $value['customerinfo']['Name'];
            $ndata['业务员名'] = $value['bussinfo']['Name'];
            $ndata['通话时间'] = $value['AddTime'];
            if(mb_strpos($value['Content'],'通话号码:')!==false){
                $ndata['回访内容'] = mb_substr($value['Content'],16);
            }else{
                $ndata['回访内容'] = $value['Content'];
            }
            // if(!empty($value['shuqiinfo']['summaryContent'])){
            //     $ndata['总结内容'] = $value['shuqiinfo']['summaryContent'];
            // }
            if(!empty($value['shuqiinfo']['callContent'])){
                $ndata['通话记录'] = $value['shuqiinfo']['callContent'];
            }
            $rdata[$value['bussinfo']['UserId']][] = $ndata;
        }
        // echo json_encode($rdata,JSON_UNESCAPED_UNICODE);
        foreach ($rdata as $key => $value) {
            // dump(json_encode($value,JSON_UNESCAPED_UNICODE));
            $tsc = "你是一名拥有10年经验的销售培训专家，请对以下销售对话执行【深度四维分析】，要求：  
                    **1. 信息结构化提取**  
                    以Markdown表格输出：  
                    | 时间段 | 客户身份特征 | 核心诉求/异议 | 销售策略评估 | 关键转折点 |  
                    （示例：“02:15-03:30 | 制造业采购主管 | “价格比预期高20%“ | 直接降价缺乏价值证明 | 客户沉默后转移话题“）  
                    **2. 问题定位与分级**  
                    用⚠️符号标记以下问题并排序：  
                    - 【技术】产品参数错误（如将4小时续航说成8小时）  
                    - 【策略】未使用“痛点-后果-方案“逻辑链（如忽略客户提到的停产风险）  
                    - 【心理】被客户压制（如多次使用“可能/大概“等弱态词汇）  
                    - 【流程】错过需求挖掘时机（如客户问“能解决X问题吗“时未深度追问）  
                    **3. AI话术优化**  
                    针对每个异议点生成3种进阶应答（需包含）：  
                    - **价值重构模板**：“您关注的XX问题其实会造成[量化损失]，我们的方案通过[技术]可减少[%]损失“  
                    - **场景对比话术**：“与您目前使用的[旧方案]相比，我们客户A实施后[关键指标]提升[X]倍“  
                    - **风险转移技巧**：“如果延迟解决，您估计会在[时间维度]面临哪些新成本？“  
                    **4. 教练引导问题**  
                    提出5个让销售人员自我反思的问题，例如：  
                    - 当客户说“[具体原话]“时，其真实顾虑可能是？我们哪句话强化了这种顾虑？  
                    - 哪个时刻本可以插入客户成功案例？为什么实际没有使用？  
                    - 如果用“您能详细说说XX要求背后的原因吗“替代原来的回答，对话走向会如何变化？  
                    **附加要求**：  
                    - 对价格敏感型客户特别标注【价格谈判线索】  
                    - 用🚩标记高风险对话节点（如过早报价/过度承诺）  
                    - 输出时采用【问题】→【根因】→【优化方案】三级结构  
                    对话内容：
                    ";

                    dump($tsc.unicodeToChinese(json_encode($value,JSON_UNESCAPED_UNICODE)));exit;
            $sf = new Siliconflow();
            $rrdata =  $sf->chat_completions($tsc.unicodeToChinese(json_encode($value,JSON_UNESCAPED_UNICODE)));
            dump($rrdata);
            break;
        }
        

    }
     /**
     * 查看通话列表 由 summary 与用户交互
     * @return [type] [description]
     */
    public function summary_data(){
        $data = input('get.');
        //业务员的id
        $userid = Pub::userid();
        //权限检测
        $ismanager = Rolepower::ispower(204007);
        if ($ismanager) {
            //管理员可查看所有的，如果有筛选条件则直接筛选某个人的
            if(!empty($data['bussid'])){
                $data['where'][]= ['BussinessId',$data['bussid']];
            }
        } else {
            //业务员只能看自己的
            $data['where'][]= ['BussinessId',$userid];
        }
        //判断状态
        if(!empty($data['State'])){
            $data['where'][] = ['State',$data['State']];
            unset($data['State']);
        }
        $with = ['customerinfo','bussinfo'];
        $visible = ['CustomerId','VisitTime','BussinessId','Content','AddTime','Img','CallsessionId','bussinfo'=>['Name','UserId'],'customerinfo'=>['Name','UserName','Type','State','Scale']];
        if(get_config_value('call_center_switch')){
            $with[] = 'shuqiinfo';
            $visible['shuqiinfo'] = ['recordUrl','connectTime','disconnectTime','timeConsume','sessionId','status','callContent','summaryContent'];
        }
        //获取客户咨询记录中对应的id
        $Customervisit = new Customervisit;
        //筛选关键词
        if(!empty($data['SearchKey'])){
            $Customervisit = $Customervisit->hasWhere('customerinfo',[['Name','like','%'.$data['SearchKey'].'%']]);
        }
        $data['order'] = 'customervisit.AddTime desc';
        // $Customervisit = $Customervisit->where('BussinessId',$userid);
        // $Customervisit = $Customervisit->where('AddTime', '>=', $data['startValue'])->where('AddTime', '<=', $data['endValue'] . ' 25:00');
        $Customervisit = $Customervisit->with($with);
        $Customervisit = $Customervisit->visible($visible);
         // dump($data);
        $data = init_where($data, ['time' => 'Customervisit.AddTime']);
        if(substr($data['startValue'],0,10)==substr($data['endValue'],0,10)){
            $data['p_limit'] = 999;
        }
        $rdata = come_model_option($data,$Customervisit,true);
        $ndata['list'] = $rdata['rdata']->select();
        if(!empty($rdata['data']['count'])){
            $ndata['pageinfo'] = ['pageindex' => $data['pageindex'], 'pagemax' => $rdata['data']['count'],'count'=>$rdata['count']];
        }
        return $ndata;
    }
    /**
     * 查看通话列表 由 summary_data 函数处理数据
     * @return [type] [description]
     */
    public function summary()
    {
        $data = self::summary_data();
        $idata = input('get.');
        $datesub = strtotime(date('Y-m-d',strtotime($idata['startValue']))) - strtotime(date('Y-m-d',strtotime($idata['endValue'])));
        $lsdata = $data['list'];
        $chatdata = [];
        $trlist = [];
        //统计数据信息
        if($datesub <= 3600*25){//时间差小于25小时，按照一天统计数据，按小时统计
            $subdata['star'] = 11;
            $subdata['length'] = 2;                
        }else{//按天统计数据
            $subdata['star'] = 8;
            $subdata['length'] = 2;      
        }
        foreach ($lsdata as $key => $value) {
            if(empty($chatdata[$value['bussinfo']['UserId']])){
               $chatdata[$value['bussinfo']['UserId']]['name'] = $value['bussinfo']['Name'];
               $chatdata[$value['bussinfo']['UserId']]['UserId'] = $value['bussinfo']['UserId'];
            }
            if(empty($chatdata[$value['bussinfo']['UserId']]['rdata'][substr($value['VisitTime'],$subdata['star'],$subdata['length'])])){
                $chatdata[$value['bussinfo']['UserId']]['rdata'][substr($value['VisitTime'],$subdata['star'],$subdata['length'])] = 1;
                if(empty($trlist[substr($value['VisitTime'],$subdata['star'],$subdata['length'])])){
                    $trlist[substr($value['VisitTime'],$subdata['star'],$subdata['length'])] = 1;
                }
            }else{
                $chatdata[$value['bussinfo']['UserId']]['rdata'][substr($value['VisitTime'],$subdata['star'],$subdata['length'])]++; 
            }
        }
        $nindex = 0;
        foreach ($trlist as $key => $value) {
            $res['categories'][$nindex++] = $key;//时间入栈
        }
        if(empty($res['categories'])){
            return moerr('暂无数据'); 
        }
        sort($res['categories']);//按顺序从新排序
        foreach ($chatdata as $kk => $vv) {
            $ndata = [];
            foreach ($res['categories'] as $key => $value) {
                if(empty($vv['rdata'][$value])){
                    $ndata[] = 0;
                }else{
                    $ndata[] = $vv['rdata'][$value];
                }
                $res['series'][$vv['UserId']]=array_merge($vv,['data'=>$ndata]);
            }
        }
        $ndata =[];
        //删去数组的id索引
        if(!empty($res['series'])){
            foreach ($res['series'] as $key => $value) {
                $ndata[] = $value;
            }
        }
        $res['series'] = $ndata;
        $data['summary_data'] = $res;
        return myok($data);
    }

    public function wecaht_summary()
    {
        $data = self::wecaht_summary_data();
        $idata = input('get.');
        $datesub = strtotime(date('Y-m-d',strtotime($idata['startValue']))) - strtotime(date('Y-m-d',strtotime($idata['endValue'])));
        $lsdata = $data['list'];
        $chatdata = [];
        $trlist = [];
        //统计数据信息
        if($datesub <= 3600*25){//时间差小于25小时，按照一天统计数据，按小时统计
            $subdata['star'] = 11;
            $subdata['length'] = 2;                
        }else{//按天统计数据
            $subdata['star'] = 8;
            $subdata['length'] = 2;      
        }
        foreach ($lsdata as $key => $value) {
            if(empty($chatdata[$value['bussinfo']['BussinessId']])){
               $chatdata[$value['bussinfo']['BussinessId']]['name'] = $value['bussinfo']['nickname'];
               $chatdata[$value['bussinfo']['BussinessId']]['BussinessId'] = $value['bussinfo']['BussinessId'];
            }
            if(empty($chatdata[$value['bussinfo']['BussinessId']]['rdata'][substr($value['timestamp'],$subdata['star'],$subdata['length'])])){
                $chatdata[$value['bussinfo']['BussinessId']]['rdata'][substr($value['timestamp'],$subdata['star'],$subdata['length'])] = 1;
                if(empty($trlist[substr($value['timestamp'],$subdata['star'],$subdata['length'])])){
                    $trlist[substr($value['timestamp'],$subdata['star'],$subdata['length'])] = 1;
                }
            }else{
                $chatdata[$value['bussinfo']['BussinessId']]['rdata'][substr($value['timestamp'],$subdata['star'],$subdata['length'])]++; 
            }
        }
        $nindex = 0;
        foreach ($trlist as $key => $value) {
            $res['categories'][$nindex++] = $key;//时间入栈
        }
        sort($res['categories']);//按顺序从新排序
        foreach ($chatdata as $kk => $vv) {
            $ndata = [];
            foreach ($res['categories'] as $key => $value) {
                if(empty($vv['rdata'][$value])){
                    $ndata[] = 0;
                }else{
                    $ndata[] = $vv['rdata'][$value];
                }
                $res['series'][$vv['BussinessId']]=array_merge($vv,['data'=>$ndata]);
            }
        }
        $ndata =[];
        //删去数组的id索引
        foreach ($res['series'] as $key => $value) {
            $ndata[] = $value;
        }
        $res['series'] = $ndata;
        $data['summary_data'] = $res;
        return myok($data);
    }

    public function wecaht_summary_data(){

        $data = input('get.');
        $data['p_limit'] = 100;//微信消息默认获取100条
        //record 记录中在这个范围内的记录，联合查询， 需要根据客户的id进行排序，
        $records = new Apiyunkerecords;

        //业务员的id
        $userid = Pub::userid();
        //权限检测
        $ismanager = Rolepower::ispower(204007);
        if ($ismanager) {
            //管理员可查看所有的，如果有筛选条件则直接筛选某个人的
            if(!empty($data['bussid'])){
                $records = $records->hasWhere('bussinfo',['BussinessId'=>$data['bussid']]);
            }
        } else {
            //业务员只能看自己的
            $records = $records->hasWhere('bussinfo',['BussinessId'=>$userid]);
        }

         //跳过微信群
        $records = $records->where('roomid','');

        //如果关联客户则直接跳转，不关联直接显示
        if(!empty($data['startValue'])&& !empty($data['endValue'])){
            $records = $records->where('time','<=',strtotime($data['endValue'].' 24:00')*1000);
            $records = $records->where('time','>=',strtotime($data['startValue'].' 00:00')*1000);
        }else{
            return myerr('缺少时间参数');
        }
        //关键词
        if(!empty($data['SearchKey'])){
            $records = $records->where('text','like','%'.$data['SearchKey'].'%');
        }

        $with = ['customerwechatinfo','bussinfo'];
        $visible = ['CustomerId','VisitTime','BussinessId','Content','AddTime','Img','CallsessionId','bussinfo'=>['Name','UserId'],'customerinfo'=>['Name','UserName','Type','State','Scale']];
        $data['order'] = 'talker desc,timestamp asc';
        $records = $records->with($with);
        // $records = $records->visible($visible);
        // $data = init_where($data, ['time' => 'Customervisit.AddTime']);
        if(substr($data['startValue'],0,10)==substr($data['endValue'],0,10)){
            $data['p_limit'] = 999;
        }
        $rdata = come_model_option($data,$records,true);
        $ndata['list'] = $rdata['rdata']->select();
        foreach ($ndata['list'] as $key => $value) {
            $ndata['list'][$key]['timestamp'] = date('Y-m-d H:i:s',$value['timestamp']/1000);
        }
        if(!empty($rdata['data']['count'])){
            $ndata['pageinfo'] = ['pageindex' => $data['pageindex'], 'pagemax' => $rdata['data']['count'],'count'=>$rdata['count']];
        }
        return $ndata;
    }

    /**
     * 查看管理通话列表
     * @return [type] [description]
     */
    public function tellist()
    {
        $data = input('get.');
        $data['Type'] = 'customer';
        //获取客户咨询记录中对应的id
        $cuidlist = Customervisit::distinct(true);
        $cuidlist = $cuidlist->where('BussinessId', Pub::userid());
        $culist = $cuidlist->where('AddTime', '>=', $data['startValue'])->where('AddTime', '<=', $data['endValue'] . ' 25:00')->order('AddTime asc')->column('Content','CustomerId');
        $cuidlist=[];
        foreach ($culist as $key => $value) {
            $cuidlist[] = $key;
        }

        $data = init_where($data, ['time' => false, 'bussid' => false]);
        $data['where'][] = ['CustomerId', 'in', $cuidlist];
        $list = Customermodel::usergetlist($data, 'mana');
        foreach ($list['list'] as $key => $value) {
            //客户回访记录
            $string = $culist[$value['CustomerId']];
            $string = str_replace("\n", "", $string);
            $string = str_replace(" ", "", $string);
            $list['list'][$key]['customertext'] = $string;
            if (!empty($value['guard_state'])) {
                $list['list'][$key]['GState'] = '保护中';
            } else {
                $list['list'][$key]['GState'] = '';
            }

            if (!empty($value['bussinfo']['Name'])) {
                $list['list'][$key]['Bname'] = $value['bussinfo']['Name'];
            } else {
                $list['list'][$key]['Bname'] = '暂无';
            }
        }
        $list['tr']['title'] = ['客户名称', '负责人', '状态', '查看信息', '最后沟通时间', '登记时间', '企业分类', '产废规模', '客户保护'];
        $list['tr']['key'] = ['Name', 'Bname', 'State', 'CustomerId', 'LastTime', 'AddTime', 'Type', 'Scale', 'GState','customertext'];
        $list['tr']['show'] = [true, false, true, true, true, false, false, false, false];
        return myok($list);
    }

    /**
     * 设置近期拨打电话的客户
     */
    public function set_recent_phone($CustomerId){
        $tel_a = Cache::get('recent_phone');
        if(empty($tel_a)){
            $tel_a = [];
        }else{
            $tel_a = json_decode($tel_a,true);

        }
        $tel_a[$CustomerId] = ['time'=>time(),'BussinessId'=>pub::userid()];
        Cache::set('recent_phone',json_encode($tel_a),43200);
        return sok();
    }

    public function test(){
        // self::set_recent_phone(rand(100,999));
        $a = self::get_recent_phone();
        $new = [];
        foreach ($a as $key => $value) {
            if($key>250){
                $new[] = $value;
            }
        }
        Cache::set('recent_phone',$new,3600);
    }

    /**
     * 获取已经打过电话的客户
     * @return [type] [description]
     */
    public function get_recent_phone($customerId=''){
        $sb = Cache::get('recent_phone');
        if(empty($sb)){
            return '';
        }else{
            $sb = json_decode($sb,true);
        }
        if(empty($customerId)){
            //不需要不需要客户id 返回整个数组
            foreach ($sb as $key => $value) {
                if(($value['time']+36000)>time()){
                    $data[] = $key;
                }
            }
            if(!empty($data)){
                return implode(',',$data);
            }else{
                return '';
            }
               
        }else{
            //传入客户id 的话，返回指定的数据
            if(empty($sb[$customerId])){
                self::set_recent_phone($customerId);
                return false;
            }else{
                return $sb[$customerId];
            }
        }

    }

    /**
     * 获取电话号码
     * @return [type] [description]
     */
    public function get_phone()
    {
        $id = input('id');
        $userid = Pub::userid();
        $must = input('must');//强制拨打电话 无视之前播过号
        // $call_center = input('call_center');
        $link_token = input('link_token');//获取连接token 为空则不使用
        if (empty($id)) {
            return myerr('缺少参数，请重新尝试');
        }
        $Customer = Customermodel::get($id);
        if ($Customer->guard_state && $Customer->BussinessId !== $userid && !Rolepower::ispower(204007)) {
            return myerr('客户处于保护期无法查看');
        }
        $hasclaim = Customermodel::getHasClaim($Customer);
        $tel = '';
        if (!empty($Customer['Tel'])) {
            $tel = $Customer['Tel'];
        }
        if (!empty($Customer['UserTel'])) {
            $tel = $Customer['UserTel'];
        }
        if(strlen($tel)<5){
            return myerr($tel.'客户电话号码错误');
        }
        if (!empty($tel)) {
            //设置已经联系过的
            $sb = self::get_recent_phone($id);
            if ($sb==false||($sb['time']+43200)<time()||$sb['BussinessId']==$userid || !empty($must) || $sb == $userid) {
                //判断是否启用Pc 电话 呼叫同步助手
                if(!empty($link_token)){
                    $sb = Telpcphone::set_customer_phone($link_token,$tel);
                    self::set_recent_phone($id);
                    return myok(['tel' => $tel,'msg'=>$sb['msg'],'has_claim' => $hasclaim]);
                }
                //没有检测到
                // Cache::set('Customer_Tel' . $tel, $userid, 43200);
                // Cache::tag('customerTel',['Customer_Tel' . $tel]);
                //判断是否开启了电话中转服务 是否必须回拨中心
                if(!empty(get_config_value('call_center_switch'))){
                    $myuser = Telbind::get($userid);
                    if (!empty($myuser)) {
                        //回拨电话
                        $teltool = new Teltool();
                        $req = $teltool->dial($tel,$myuser->Iphone);

                        if (!$req['code']) {
                            self::set_recent_phone($id);
                            return myok(['call_center'=>'error','msg'=>$req['msg'],'tel'=>$tel, 'has_claim' => $hasclaim]);
                        }else{
                            self::set_recent_phone($id);
                            return myok(['call_center'=>'success','msg'=>'已通知回拨中心，请等待接听电话','tel'=>$tel,'has_claim'=>$hasclaim,'sessionId'=>$req['msg']['data']]);
                        }
                    }
                    //返回
                }
                self::set_recent_phone($id);
                return myok(['tel' => $tel, 'has_claim' => $hasclaim]);
            } else {
                //检测到重复数据
                $userdata = Usermodel::get($sb['BussinessId']);
                return myerr('此客户在12小时内【' . $userdata['Name'] . '】有联系客户,是否继续拨打？', '', 'confirm');
            }

        }
        return myerr('暂无该客户电话');
    }

    /**
     * 基础信息
     * @return [type] [description]
     */
    public function getinfo()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少参数，请重新尝试');
        }
        $ismanager = Rolepower::ispower(204007);
        if ($ismanager) {
            $type = 'mana';
        } else {
            $type = 'buss';
        }
        $data = Customermodel::user_getinfo($id, $type);
        if (empty($data)) {
            return myerr('没有找到此客户');
        }
        $data['power_change_buss'] = $ismanager;
        if (!empty(input('reinfo'))) {
            $data['agentlist'] = Customermodel::getagentlist($id);
        }
        //客户所属区域控制
        $data['input_street_area'] = get_config_value('input_street_area');

        return myok($data);
    }

    /**
     * [将数据发给ai模型]
     * @return [type] [description]
     */
    public function chat_summary(){
        set_time_limit(300);
        $content = input('msg');
        if(empty($content)){
            return moerr('缺少沟通内容');
        }
        $sf = new Siliconflow();
        $data =  $sf->chat_completions($content);
        return myok($data);
    }

    /**
     * 解析语音沟通内容
     * @return [type] [description]
     */
    public function asr_phone(){
        set_time_limit(300);
        $url = input('url');
        if(empty($url)){
            return moerr('缺少地址信息');
        }
        $yasr = new Yhpcsoftasr();
        $data =  $yasr->phone($url);
        if($data['code']){
            return myok($data['msg']);
        }else{
            return moerr($data['msg']);
        }
    }

    /**
     * 业务大厅获取业务人员沟通通话记录
     * @return [type] [description]
     */
    public function hall_get_call_records(){
        //获取查询时间
        $beginTime = input('beginTime');
        $endTime = input('endTime');
        $beginTime = empty($beginTime)?date('Y-m-d 00:00:00',time()):$beginTime;
        $endTime = empty($endTime)?date('Y-m-d 24:00:00',time()):$endTime;
        $user = UserModel::getinfo();
        $yk = new Yunke();
        $data =  $yk->call_records($beginTime,$endTime);
        // $data =  $yk->call_records($beginTime,$endTime,$user->Iphone);
        return myok($data);
    }

    /**
     * 微信录音key转为可播放音频地址
     * @return [type] [description]
     */
    public function yunkegetwechatAmrTrans(){
        $yk = new Yunke();
        return $yk->getwechatAmrTrans();
    }

    /**
     * 业务大厅 获取客户数据
     * @param  boolean $nulltest [description]
     * @return [type]            [description]
     */
    public function customerhall($recent_phone_validate = true)
    {
        $key = trim(input('searchkey'));
        if ($key == "%") {
            return moerr('非法参数');
        }
        $idata = input('post.');
        //排序
        if (!empty($idata['order'])) {
            switch ($idata['order']) {
                case 'count_asc':
                    $sdata['order'] = 'VisitCount asc';
                    break;
                case 'count_desc':
                    $sdata['order'] = 'VisitCount desc';
                    break;
                case 'time_asc':
                    $sdata['order'] = 'LastTime asc,VisitCount asc';
                    break;
                case 'time_desc':
                    $sdata['order'] = 'LastTime desc,VisitCount asc';
                    break;
            }
        }else{
            $sdata['order'] = 'LastTime asc,VisitCount asc';
        }
        $sdata['order'] = $sdata['order'] . ',BussinessId asc';

        //输出限制
        if (empty($idata['limit'])) {
            $sdata['limit'] = '30';
            //分页加载
            if (!empty($idata['pages'])) {
                $sdata['limit'] = [$sdata['limit'] * $idata['pages'], $sdata['limit']];
            }
        } else if ($idata['limit'] !== '-1') {
            //分页加载
            if (!empty($idata['pages'])) {
                $sdata['limit'] = [$idata['limit'] * $idata['pages'], $idata['limit']];
            } else {
                $sdata['limit'] = $idata['limit'];
            }
        }
        //客户归属
        if (!empty($idata['Belong'])) {
            switch ($idata['Belong']) {
                case 'my':
                    $sdata['where'][] = ['BussinessId', Pub::userid()];
                    break;
                case 'other':
                    $sdata['where'][] = ['BussinessId', '<>', Pub::userid()];
                    break;
                case 'empty':
                    $sdata['where'][] = ['BussinessId', 'null'];
                    break;
            }
        }
        //程序第一次会进行手机号拨打验证限制，
        //删除最近打过电话的客户
        //如果在搜索到为空的时候，还会将之前打过的显示出来
        if($recent_phone_validate){
            $recent_a = self::get_recent_phone();
            if(!empty($recent_a)){
                $sdata['where'][] = ['(CustomerId not in('.$recent_a.'))'];
            }
        }

        //筛选 状态
        if (!empty($idata['State']) && $idata['State'] !== '-1') {
            $sdata['where'][] = ['State', 'in', $idata['State']];
        } else {
            $sdata['where'][] = ['State', '<>', Customermodel::STATEOK];
        }

        //筛选 规模
        if (!empty($idata['Scale'])) {
            $sdata['where'][] = ['Scale', 'in', $idata['Scale']];
        }

        //筛选 分类
        if (!empty($idata['Type'])) {
            $sdata['where'][] = ['Type', 'in', $idata['Type']];
        }

        //筛选 呼叫黑名单客户 非空则判断是否为假
        if (!empty($idata['call_black_blacklist']) && $idata['call_black_blacklist']) {
            $sdata['where'][] = ['length(UserTel) = 11|| length(Tel) = 11'];
        }
        //筛选 呼叫黑名单客户 非空则判断是否为假
        if (empty($idata['call_black_blacklist'])||!$idata['call_black_blacklist']) {
            $sdata['where'][] = ['(Type  <> "呼叫黑名单客户")or(Type is null)'];
        }

        //通用筛选，删去企业电话和联系人电话都为空的客户
        if (!empty($idata['jump_tel_phone_state'])&&$idata['jump_tel_phone_state']){
            $sdata['where'][] = ['(Tel is not null or UserTel is not null)'];
        }
        
        //定位
        if (!empty($idata['lat'])) {
            $sdata['field'] = [str_distance($idata['lat'], $idata['lon'])];
            if (!empty($idata['order']) && $idata['order'] == 'distance') {
                $sdata['order'] = 'distance asc';
            }
        }

        //关键词
        if (!empty($key)) {
            $sdata['where'][] = ['(Name like "%' . $key . '%")or(Address like "%' . $key . '%")or(UserName like "%' . $key . '%")or(UserTel like "%' . $key . '%")or(Tel like "%' . $key . '%")'];
        }

        //如果此人是业务员 增加条件
        if (CUSTOMER_BIND_SWITCH && !Rolepower::ispower(204007)) {
            $str = '(BussinessId = ' . Pub::userid() . ')';
            $str = $str . 'or';
            $str = $str . '(BussinessId is null)';
            $str = $str . 'or';
            $str = $str . '(';
            $str = $str . '(LastTime <"' . date('Y-m-d H:i:s', time() - (3600 * 24 * CUSTOMER_BIND_INVALID_DAY)) . '")';
            $str = $str . ' or ';
            $str = $str . '(';
            $str = $str . '(LastTime is null ) and (AddTime < "' . date('Y-m-d H:i:s', time() - (3600 * 24 * CUSTOMER_BIND_DAY)) . '")';
            $str = $str . ')';
            $str = $str . ')';
            $sdata['where'][] = [$str];
        }

        //拜访时间限制
        if (!empty($idata['starttime'])) {
            $sdata['where'][] = ['(LastTime >= "' . $idata['starttime'] . '")'];
        }

        //拜访时间限制
        if (!empty($idata['endtime'])) {
            $sdata['where'][] = ['(LastTime <= "' . $idata['endtime'] . '")'];
        }

        $sdata['Type'] = 'customer';

        //如果pc则以分页形式显示
        $idata['is_pc'] = empty($idata['is_pc']) ? false : true;
        $idata['is_page'] = $idata['is_pc'] ? true : false;

        //客户列表
        if (Rolepower::ispower(204007)) {
            $data = Customermodel::usergetlist($sdata, 'mana', $idata['is_page']);
        } else {
            $data = Customermodel::usergetlist($sdata, 'buss', $idata['is_page']);
        }
        if($recent_phone_validate && empty($data['list'])){
            return self::customerhall(false);
        }
        $data['recent_phone_validate'] = $recent_phone_validate;
        
        return myok($data);
    }
    /**
     * 获取客户业务大厅的基础数据
     * @return [type] [description]
     */
    public function customerhall_init(){
        $data['Scalelist'] = array_del_empty(Customermodel::distinct(true)->column('Scale'));
        $data['Typelist'] = array_del_empty(Customermodel::distinct(true)->column('Type'));
        $data['Statelist'] = Customermodel::getStatusText();
        //获取云客销售系统的开关，如果开通，则开始获取客户电话
        $data['yunke_switch'] = get_config_value('yunke_switch');
        if($data['yunke_switch']){
            $yk = new Yunke();
            $user = UserModel::getinfo();
            $sb = $yk->getuser_by_phone($user->Iphone,false);
            if($sb['code']==false){
                $data['yunke_switch'] = false;
            }
        }
        $data['ismanager'] = Rolepower::ispower(204007);
        return myok($data);
    }

    /**
     * 认领客户
     * @return [type] [description]
     */
    public function claim_customer()
    {
        $id = input('id');
        $sb = Customermodel::get($id);
        if (empty($sb)) {
            return moerr('没有找到您需要的客户信息');
        }
        $data = Customermodel::claim($id, Pub::userid(), $sb);
        if (!$data['code']) {
            return myerr('认领失败');
        } else {
            return myok($data['msg']);
        }
    }

    /**
     * 获取评论列表
     * id  composerid
     * @return [type] [description]
     */
    public function getvisitlist()
    {
        $id = input('id');
        $Customer = Customermodel::get($id);
        if ($Customer->guard_state && $Customer->BussinessId !== Pub::userid() && !Rolepower::ispower(204007)) {
            return myerr('客户处于保护期无法查看');
        }
        $data = Customervisit::getlist($id);
        return myok($data);
    }

    /**
     * 查看管理列表
     * @return [type] [description]
     */
    public function list()
    {
        $data = input('get.');
        $data['Type'] = 'customer';
        $data = init_where($data);
        $list = Customermodel::usergetlist($data, 'buss');
        foreach ($list['list'] as $key => $value) {
            if (!empty($value['guard_state'])) {
                $list['list'][$key]['GState'] = '保护中';
            } else {
                $list['list'][$key]['GState'] = '';
            }

            if (!empty($value['bussinfo']['Name'])) {
                $list['list'][$key]['Bname'] = $value['bussinfo']['Name'];
            } else {
                $list['list'][$key]['Bname'] = '暂无';
            }
        }
        $list['tr']['title'] = ['客户名称', '业务员', '状态', '查看信息', '沟通时间', '登记时间', '企业分类', '产废规模', '客户保护'];
        $list['tr']['key'] = ['Name', 'Bname', 'State', 'CustomerId', 'LastTime', 'AddTime', 'Type', 'Scale', 'GState'];
        $list['tr']['show'] = [true, true, true, true, false, false, false, false, false];
        return myok($list);
    }

    /**
     * 客户通讯录
     * @return [type] [description]
     */
    public function companylist()
    {
        $key = trim(input('searchkey'));
        if ($key == "%") {
            return moerr('非法参数');
        }
        $idata = input('post.');
        //定位
        if (!empty($idata['lat'])) {
            $sdata['field'] = [str_distance($idata['lat'], $idata['lon'])];
            $sdata['order'] = 'distance asc';
        }
        //没有定位直接显示关键词
        if (!empty($key)) {
            $sdata['where'][] = ['(Name like "%' . $key . '%")or(Address like "%' . $key . '%")or(UserName like "%' . $key . '%")or(UserTel like "%' . $key . '%")or(Tel like "%' . $key . '%")'];
        } else {
            $sdata['where'][] = ['Lat', 'not null'];
        }
        //输出限制
        if (empty($idata['limit'])) {
            $sdata['limit'] = '30';
            //分页加载
            if (!empty($idata['pages'])) {
                $sdata['limit'] = [$sdata['limit'] * $idata['pages'], $sdata['limit']];
            }
        } else if ($idata['limit'] !== '-1') {
            //分页加载
            if (!empty($idata['pages'])) {
                $sdata['limit'] = [$idata['limit'] * $idata['pages'], $idata['limit']];
            } else {
                $sdata['limit'] = $idata['limit'];
            }
        }
        $sdata['Type'] = 'customer';
        //客户列表
        if (Rolepower::ispower(204007)) {
            $data = Customermodel::usergetlist($sdata, 'mana', false);
        } else {
            $data = Customermodel::usergetlist($sdata, 'buss', false);
        }

        //企业列表
        $idlist = [];
        foreach ($data['list'] as $key => $value) {
            if (!empty($value['CompanyId'])) {
                $idlist[] = $value['CompanyId'];
            }
        }
        $sdata['Type'] = 'company';
        $sdata['where'][] = ['CompanyId', 'not in', $idlist];
        $company = Company::usergetlist($sdata, 'buss', false);
        $idlist = [];//获取企业id
        $company_customer = [];//企业id 对应的客户表
        $ncompanylist = [];
        foreach ($company['list'] as $key => $value) {
            $idlist[] = $value['CompanyId'];
            $ncompanylist[$value['CompanyId']] = $value;
        }
        //定位
        if (!empty($idata['lat'])) {
            $nsdata['field'] = [str_distance($idata['lat'], $idata['lon'])];
            $nsdata['order'] = 'distance asc';
        }
        $nsdata['where'][] = ['CompanyId', 'in', $idlist];
        //客户列表
        if (Rolepower::ispower(204007)) {
            $company_customer = Customermodel::usergetlist($nsdata, 'mana', false);
        } else {
            $company_customer = Customermodel::usergetlist($nsdata, 'buss', false);
        }
        if (!empty($company_customer['list'])) {
            $data['list'] = array_merge($data['list'], $company_customer['list']);
        }
        foreach ($data['list'] as $key => $value) {
            // //移除能查到客户表的企业信息
            if (!empty($value['CompanyId']) && !empty($ncompanylist[$value['CompanyId']])) {
                unset($ncompanylist[$value['CompanyId']]);
            }
        }
        $company['list'] = [];
        foreach ($ncompanylist as $key => $value) {
            $company['list'][] = $value;
        }
        $data['company'] = $company;
        $data['Scalelist'] = array_del_empty(Customermodel::distinct(true)->column('Scale'));
        $data['Typelist'] = array_del_empty(Customermodel::distinct(true)->column('Type'));
        return myok($data);
    }

    /**
     * 地图查看信息
     * @return [type] [description]
     */
    public function maplist()
    {
        $key = trim(input('searchkey'));
        if ($key == "%") {
            return moerr('非法参数');
        }
        $idata = input('post.');
        $state = input('state');
        $idata['state'] = '-1';
        $sdata = init_where($idata);
        //定位
        if (!empty($idata['lat'])) {
            $sdata['field'] = [str_distance($idata['lat'], $idata['lon'])];
            $sdata['order'] = 'distance';
        }
        //客户归属
        if (!empty($idata['customer_belong'])) {
            switch ($idata['customer_belong']) {
                case 'my':
                    $sdata['where'][] = ['BussinessId', Pub::userid()];
                    break;
                case 'other':
                    $sdata['where'][] = ['BussinessId', '<>', Pub::userid()];
                    break;
                case 'empty':
                    $sdata['where'][] = ['BussinessId', 'null'];
                    break;
            }
        }
        // dump($sdata['where']);

        //分类
        if (!empty($idata['type'])) {
            $sdata['where'][] = ['Type', 'in', $idata['type']];
        }
        //规模
        if (!empty($idata['scale'])) {
            $sdata['where'][] = ['Scale', 'in', $idata['scale']];
        }
        //规模
        if (!empty($state)) {
            $sdata['where'][] = ['State', 'in', $state];
        }
        //没有定位直接显示关键词
        if (!empty($key)) {
            $sdata['where'][] = ['Name', 'like', '%' . $key . '%'];
        }

        if (empty($idata['limit'])) {
            $sdata['limit'] = '30';
        } else if ($idata['limit'] !== '-1') {
            $sdata['limit'] = $idata['limit'];
        }

        $sdata['Type'] = 'customer';
        $sdata['where'][] = ['Lat', 'not null'];

        if (Rolepower::ispower(204007)) {
            $data = Customermodel::usergetlist($sdata, 'mana', false);
        } else {
            $data = Customermodel::usergetlist($sdata, 'buss', false);
        }
        $data['Scalelist'] = array_del_empty(Customermodel::distinct(true)->column('Scale'));
        $data['Typelist'] = array_del_empty(Customermodel::distinct(true)->column('Type'));
        return myok($data);
    }

    /**
     * 添加回访信息
     * @return [type] [description]
     */
    public function addvisit()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少参数，请重新尝试');
        }
        $customer = Customermodel::get($id);
        if (empty($customer)) {
            return myerr('没有找到客户信息');
        }

        $idata = input('post.');
        if (empty($idata['Content']) && empty($idata['Img'])) {
            return myerr('请输入回访内容');
        }
        //保存记录
        $ndata = new Customervisit;
        if (empty($idata['VisitTime'])) {
            $idata['VisitTime'] = date('Y-m-d H:i:s', time());
        }
        $ndata['BussinessId'] = Pub::userid();
        $ndata['CustomerId'] = $id;
        $ndata['VisitTime'] = $idata['VisitTime'];
        $ndata['AddTime'] = date('Y-m-d H:i:s', time());
        //新增回访记录的seessionId,由回拨中心产生回访id
        if(!empty($idata['CallsessionId'])){
            $ndata['CallsessionId'] = $idata['CallsessionId'];
        }

        if (!empty($idata['Content'])) {
            $ndata['Content'] = $idata['Content'];
        }
        if (!empty($idata['Img'])) {
            $ndata['Img'] = $idata['Img'];
        }
        $ndata->save();
        //修改统计
        if ($customer->LastTime < $ndata['VisitTime']) {
            $customer->LastTime = $ndata['VisitTime'];
        }
        $customer->VisitCount = $customer->VisitCount + 1;
        $customer->save();
        // 如果预约回访有值，添加预约回访记录
        if ($idata['SubscribeContent'] != '') {
            $subscribe = [
                'CustomerId' => $id,
                'SubscribeTime' => $idata['SubscribeTime'],
                'u_id' => Pub::userid(),
                'Content' => $idata['SubscribeContent'],
            ];
            if (!empty($idata['SubscribeImg'])) {
                $subscribe['Img'] = $idata['SubscribeImg'];
            }
            (new SubscribeModel())->addSubscribe($subscribe);
        }
        //返回ok
        return myok('记录成功');
    }

    /**
     * 修改企业信息
     * @return [type] [description]
     */
    public function reinfo()
    {
        $data = input('post.');
        $id = input('id');
        if (!empty($id)) {
            $customer = Customermodel::user_getinfo($id);
        } else {
            return myerr('缺少需要的信息');
        }
        //为空则给企业返回修改信息
        if (empty($data)) {
            return myerr('缺少需要修改的信息');
        }
        //修改企业信息
        Customermodel::user_reinfo($data);
        return myok('修改成功');
    }

    /**
     * 获取创建前的数据
     * @return [type] [description]
     */
    public function getcreateinitinfo()
    {
        $data['StateList'] = Customermodel::getStatusText();
        $data['ScaleList'] = array_del_empty(Customermodel::distinct(true)->column('Scale'));
        $data['TypeList'] = array_del_empty(Customermodel::distinct(true)->column('Type'));
        $data['agentlist'] = Customermodel::getagentlist();
        //客户所属区域控制
        $data['input_street_area'] = get_config_value('input_street_area');
        return myok($data);
    }

    /**
     * 新增客户信息
     * @return [type] [description]
     */
    public function createinfo()
    {
        $data = input('post.');
        if (empty($data)) {
            return myerr('缺少需要的信息');
        }
        $customerid = Customermodel::user_create($data);
        return myok($customerid);
    }

    /**
     * 生成产废单位信息
     * @return [type] [返回企业id]
     */
    public function create_companyinfo()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr();
        }
        $sb = Customermodel::get($id);
        if (empty($sb)) {
            return myerr();
        }
        if (!empty($sb['CompanyId'])) {
            return myerr('此客户以有绑定的产废单位');
        }
        $data['username'] = $sb->UserName;
        $data['usertel'] = $sb->UserTel;
        $data['name'] = $sb->Name;
        $data['tel'] = $sb->Tel;
        $data['lon'] = $sb->Lon;
        $data['lat'] = $sb->Lat;
        $data['address'] = $sb->Address;
        $data['isplanform'] = $sb->isPlanform;
        $data['LicenseNumber'] = $sb->LicenseNumber;
        $data['StreetId'] = $sb->StreetId;

        $companyid = Company::user_create($data, 'buss');

        $sb->CompanyId = $companyid;
        $sb->BussinessId = Pub::userid();
        $sb->BindTime = date('Y-m-d H:i:s', time());
        $sb->save();
        return myok($companyid);
    }

    /**
     * 图片上传
     * @return [type] [description]
     */
    public function upimg()
    {
        $type = 'customer';
        try {
            $file = request()->file('img');
        } catch (\Exception $e) {
            return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        if (!is_null($file)) {
            try {
                $save_path = Env::get('root_path') . 'public/static' . '/upimg/customer/' . $type . '/';
                $info = $file->validate(["size" => 50000000, 'ext' => 'jpg,png,gif'])->rule("date")->move($save_path);
                //echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
                $image = \think\Image::open($save_path . '/' . $info->getSaveName());
                $image->thumb(2000, 2000)->save($save_path . '/' . $info->getSaveName());
                if ($info) {//getSaveName();
                    $p = $info->getFilename();
                    return json_encode(['status' => 'ok', 'data' => SERVERURL . 'static/upimg/customer/' . $type . '/' . date('Ymd', time()) . '/' . $p]);
                } else {
                    return json_encode(['status' => 'error', 'data' => $info->getError()]);
                }
            } catch (\Exception $e) {
                return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
            }

        } else {
            return json_encode(['status' => 'error', 'data' => '没有找到需要上传的图片']);
        }
    }


    /**
     * 判断账号是否登录
     * @return boolean [description]
     */
    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }
}
